import axios from 'axios'
import { tansParams } from '@/common/utils'
import { BaseUrl } from '@/common/config.js'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: BaseUrl,
  // 超时
  timeout: 10000,
})

// request拦截器
request.interceptors.request.use(
  config => {
    uni.getNetworkType({
      success: function (res) {
        console.log(res.networkType) //网络类型 wifi、2g、3g、4g、ethernet、unknown、none
        if (res.networkType === 'none') {
          console.log('当前无网络')
          uni.$u.toast('当前无网络')
        } else {
          console.log('有网络')
        }
      },
    })
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (uni.getStorageSync('Token') && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + uni.getStorageSync('Token') // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params)
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  res => {
    // 未设置状态码则默认成功状态
    // if (res.status != 200) {
    //   uni.showToast({
    //     title: '请求超时，请检查网络',
    //     icon: 'none',
    //     mask: false,
    //     duration: 2000,
    //   })
    // }
    console.log(res)
    const code = res.status =='200' ? res.status : res.data.meta.code ? parseInt(res.data.meta.code) : -300
    // const code = res.data.meta.code
    // 获取错误信息
    const msg = res.status =='200' ? res.errMsg : res.data.meta.message
	console.log("接口code2="+code)
    // 二进制数据则直接返回
    if (code == 401) {
      console.log(401)
      //401为无操作权限code（未传token或token失效）
      // uni.clearStorageSync()
      uni.removeStorageSync('Token')
      // uni.removeStorageSync('userInfo');
      let jump = uni.getStorageSync('isJump')
      if (!jump) {
        uni.setStorageSync('isJump', true)
        uni.navigateTo({
          url: `/packageAuth/pages/authorization/index`,
        })
      }
    } else if (code !== 401 && code !== 200) {
      uni.showToast({
        title: msg,
        icon: 'none',
        mask: false,
        duration: 2000,
      })
      //uni.$u.toast(error)
      return Promise.reject(new Error(msg))
    } else {
      return res.status =='200' ? res : res.data.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    uni.showToast({
      title: message,
      icon: 'none',
      mask: false,
      duration: 2000,
    })
    return Promise.reject(error)
  }
)

// 自定义适配器来适配uniapp语法
axios.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    console.log(config)
    var settle = require('axios/lib/core/settle')
    var buildURL = require('axios/lib/helpers/buildURL')
    uni.request({
      method: config.method.toUpperCase(),
      url:
        config.baseURL +
        buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config,
        }

        settle(resolve, reject, response)
      },
    })
  })
}

export default request
